package com.googlecode.sqldatagenerator.parser;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

import com.googlecode.sqldatagenerator.exception.SqlParseException;
import com.googlecode.sqldatagenerator.model.HasToken;
import com.googlecode.sqldatagenerator.model.dto.QueryDto;
import com.googlecode.sqldatagenerator.model.enums.SqlStatement;

public class SqlParser extends StatementParser {

    public SqlParser(Reader reader) {
        super(reader);
        groupList = new ArrayList<SyntaxGroup>(4);
        groupList.add(new TreeGroup("(", ")", null));
        groupList.add(new TreeGroup("[", "]", null));
        groupList.add(new TreeGroup("{", "}", null));
        groupList.add(new LiteralGroup("'", "'", null));
        groupList.add(new LiteralGroup("\"", "\"", null));
    }

    public QueryDto parseSql() throws IOException, SqlParseException {
        String token = readToken();
        if (token.equalsIgnoreCase(SqlStatement.SELECT.getToken())){
            return parseSelect();
        }
        if (token.equalsIgnoreCase(SqlStatement.UPDATE.getToken())){
            return parseUpdate();
        }
        if (token.equalsIgnoreCase(SqlStatement.DELETE.getToken())){
            return parseDelete();
        }
        throw tokenExpectedError(SqlStatement.SELECT,
                                 SqlStatement.UPDATE,
                                 SqlStatement.DELETE);
    }

    public QueryDto parseSelect() throws IOException {
        String token = skipUntilAnyTokenIgnoreCase(
                SqlStatement.SELECT.getToken(), 
                SqlStatement.FROM.getToken());
        return null;
    }

    public QueryDto parseUpdate() {
        // TODO Auto-generated method stub
        return null;
    }
    
    public QueryDto parseDelete() {
        // TODO Auto-generated method stub
        return null;
    }
    
    protected SqlParseException tokenExpectedError(HasToken... tokens){
        StringBuilder txt = new StringBuilder();
        txt.append("Esperava-se uma das palavras: ");
        boolean first = true;
        for (HasToken token : tokens) {
            if (first){
                first = false;
            } else {
                txt.append(", ");
            }
            txt.append(token);
        }
        return new SqlParseException(txt.toString(), intRowIndex(), intColumnIndex(), intPosition());
    }
}
